const { Controller } = require('dx-router-admin');

const dxEpay = require('dx-epay');

module.exports = class Callback extends Controller {
	constructor(ctx) {
		super(ctx);
	}
	// 支付回调
	async notify() {
		const paytype = this.$dx.request.param('paytype');
		const method = this.$dx.request.param('method');
		if (!paytype || !method) {
			console.log('paytype,method 参数不能为空');
			return this.$dx.fail('参数错误');
		}
		const pay = new dxEpay(paytype, method);
		const result = await pay.notify(this.$dx.request.event);
		let {
			resultCode, // 微信支付v2和支付宝支付判断成功的字段
			tradeState, // 微信支付v3判断支付成功的字段
			version, // 微信支付V2/v3判断返回的字段
		} = result;
		if (resultCode == 'SUCCESS' || tradeState === 'SUCCESS') {
			// 支付成功,处理业务逻辑
			await this.$dx.service.order.settlement(result);
		}
		if (paytype === 'wechat') {
			if (version === 'v3') {
				return {
					code: 'SUCCESS',
					message: '成功',
				};
			} else {
				this.$dx.response.setHeader('content-type', 'text/xml;charset=utf-8');
				return `<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>`;
			}
		} else if (paytype === 'alipay') {
			this.$dx.response.setHeader('content-type', 'text/plain');
			return 'success';
		}
	}
};
